package mspdt.ubzuuch.mn;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;
import org.taptwo.android.widget.ViewFlow.ViewLazyInitializeListener;
import org.taptwo.android.widget.ViewFlow.ViewSwitchListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.TextView;

public class AutoViewActivity extends Activity{
	
	private ViewFlow gallery;
	private CircleFlowIndicator indicator;
	private String title = "";
	private ArrayList<String> images = new ArrayList<String>();
	private TextView tv_name;
	private GalleryAdapter gal_adapter;
	private int tv_id =0;
	private ExpandableListView exp_view;
	private MainExpandableAdapter view_adapter;
	private ArrayList<String> parent_datas = new ArrayList<String>();
	private ArrayList<ArrayList<String>> child_datas = new ArrayList<ArrayList<String>>();
	private int b_id = 0;
	private String[] parent_names = {"Ерөнхий Мэдээлэл", "Фирм марк","Тогтмол үзүүлэлтүүд"};
	private int gal_pos = 0;
	private TextView full_screen;
	private int[] factory_keys={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,35,36,37,48,49};
	private String[] factory_names = {"Acura", "Audi", "BMW", "Chevrolet", "Chrysler", "Daewoo", "Daihatsu", "Dodge", "GMC", "Great Wall", "Honda", "Hummer","Hyundai",
			"Infiniti", "Isuzu", "Jaguar","Jeep","Kia","Land Rover","Lexus","Lincoln","Mazda","Mercedes Benz","Mercury","Mitsubishi","Nissan","Porsche",
			"Renault","Skoda","Ssang Yong","Subaru","Toyota","Volkswagen","Volvo","Орос","Бусад"};
	private String[] ungu = {"хар","хар саарал","цагаан","сувдан цагаан","хөх","хар хөх","мөнгөлөг","цлаан","ягаан","бор","ногоон","хар ногоон","шар","шаргал","алаг"};
	private String[] transmission = {"автомат","механик","хосолсон"};
	private String[] motor = {"0.5 литр хүртэл","0.6 литр","0.7 литр","0.8 литр","0.9 литр","1 литр","1.1 литр","1.2 литр","1.3 литр","1.4 литр","1.5 литр",
			"1.6 литр","1.7 литр","1.8 литр","1.9 литр","2.0 литр","2.1 литр","2.2 литр","2.3 литр","2.4 литр","2.5 литр","2.6 литр","2.7 литр","2.8 литр",
			"2.9 литр","3.0 литр","3.1 литр","3.2 литр","3.3 литр","3.4 литр","3.5 литр","3.6 литр","3.7 литр","3.8 литр","3.9 литр","4.0 литр","4.1 литр",
			"4.2 литр","4.3 литр","4.4 литр","4.5 литр","4.6 литр","4.7 литр","4.8 литр","4.9 литр","5.0 литр","5.1 литр","5.2 литр","5.3 литр","5.4 литр",
			"5.5 литр","5.6 литр","5.7 литр","5.8+ литр"};
	private ImageView zar_oruulah_image;
	private NetworkConnectionClass network;
  	@Override
	public void onBackPressed() {
	   finish();
	   overridePendingTransition(R.anim.left_in, R.anim.right_out);
	}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.auto_view);
		images.add("");
		initialize();
		getData();
			
	}
	@Override
	public void onResume()
	{
		findViewById(R.id.car_footer_contact).setBackgroundColor(Color.TRANSPARENT);
    	findViewById(R.id.car_footer_information).setBackgroundResource(R.drawable.footer_clicked);
		super.onResume();
	}
	private final void focusOnView(){
        new Handler().post(new Runnable() {
            @Override
            public void run() {
            	findViewById(R.id.title_scroll_view).scrollTo(findViewById(tv_id).getLeft()-10, 0);
            }
        });
    }
	public void getData()
	{
		images.clear();
		parent_datas.clear();
		child_datas.clear();
		final ProgressDialog dialog = ProgressDialog.show(AutoViewActivity.this, null, 
    			getResources().getString(R.string.dialog_please_wait), true);
    	
    			final Handler handler_view = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   if(msg.what==1)
    				   {
    					   tv_name.setText(title);
        				   gal_adapter=new GalleryAdapter(AutoViewActivity.this, images);
        				   gallery.setAdapter(gal_adapter);
        				   gallery.setFlowIndicator(indicator);
        				   //gal_adapter.notifyDataSetChanged();
        				   view_adapter = new MainExpandableAdapter(AutoViewActivity.this, parent_datas, null, child_datas, null);
        				   exp_view.setAdapter(view_adapter);
    				   }
    				   else
    					   Toast.makeText(AutoViewActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    				   dialog.dismiss();
    			      }
    			   };
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(getResources().getString(R.string.json_car_url)+1, 5000) && network.isNetworkConnected())
    				   {
    					   try {
        					   for(int i=0;i<3;i++)
        					   {
        						   parent_datas.add(parent_names[i]);
        					   }
        					   JSONfuncObject main_json_data = new JSONfuncObject();
        					   JSONObject json_data = main_json_data.getJSONfromURL(AutoViewActivity.this.getResources().getString(R.string.json_car_view_url)+b_id);
        					  
        					   int temp_id=0;
    							for(int j=0;j<factory_keys.length;j++)
    							{
    								if(factory_keys[j]==json_data.getInt("carfactory"))
    								{
    									temp_id=j;
    									break;
    								}
    							}
    							 title=json_data.getString("carmakedate")+" "+factory_names[temp_id];
    							 ArrayList<String> body0 = new ArrayList<String>();
    							 body0.add(json_data.getString("carbody"));
    							 ArrayList<String> body1= new ArrayList<String>();
    							 body1.add("Фирм марк");
    							 ArrayList<String> body2= new ArrayList<String>();
    							 body2.add(json_data.getString("carorjirsen")+" онд орж ирсэн "+transmission[json_data.getInt("cartransmisssion")]+" кроптой, "+motor[json_data.getInt("carmotor")]+" хөдөлгүүрийн багтаамжтай, "+ungu[json_data.getInt("carungu")]+" өнгийн");
    							 child_datas.add(body0);
    							 child_datas.add(body1);
    							 child_datas.add(body2);
    							 for(int k=1;k<7;k++)
    							 {
    								 String[] image_array = json_data.getString("carimage"+k).split(",");
        							 for(int j=0;j<image_array.length;j++)
        							 {
        								 if(!image_array[j].equals("") && !image_array[j].equals("null"))
        									 images.add("http://202.131.237.185/ubzuuch/web/uploads/images/carzar/"+image_array[j]);
        							 }
    							 }
    							 
            				   
    					} catch (Exception e) {
    						// TODO: handle exception
    						Log.d("TEST", "error="+e);
    					}
        				   handler_view.sendEmptyMessage(1);
    				   }
    				   else
    					   handler_view.sendEmptyMessage(0);
    				   
    			      }
    			   };
    			checkUpdate.start();
	}
	public void createTitleComponents()
	{
		//Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
		
		//Үндсэн товчлууруудын үйлдэл
		//Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		//Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(AutoViewActivity.this, ItemActivityFromDB.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(AutoViewActivity.this, SearchActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(AutoViewActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});
		findViewById(R.id.car_footer_contact).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

            	findViewById(R.id.car_footer_information).setBackgroundColor(Color.TRANSPARENT);
            	findViewById(R.id.car_footer_contact).setBackgroundResource(R.drawable.footer_clicked);
            	
				Intent intent = new Intent(AutoViewActivity.this, ContactUsActivity.class); 
				Bundle bundle = new Bundle();
				bundle.putString("contact", "Contact us");
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.bottom_in, R.anim.no_anim);
				
			}
		});
		
		//Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutoViewActivity.this, MainActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutoViewActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutoViewActivity.this, NewApartmentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutoViewActivity.this, UBActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(AutoViewActivity.this, AutomobileActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    setContentView(R.layout.auto_view);
	    initialize();
	    tv_name.setText(title);
		   gal_adapter=new GalleryAdapter(AutoViewActivity.this, images);
		   gallery.setAdapter(gal_adapter);
		   gallery.setFlowIndicator(indicator);
		   //gal_adapter.notifyDataSetChanged();
		   view_adapter = new MainExpandableAdapter(AutoViewActivity.this, parent_datas, null, child_datas, null);
		   exp_view.setAdapter(view_adapter);
	    super.onConfigurationChanged(newConfig);
	}

	public void initialize()
	{
		network=new NetworkConnectionClass(this);
		Bundle bundle = getIntent().getExtras();
		tv_id = bundle.getInt("title");
		b_id = bundle.getInt("id");
		exp_view = (ExpandableListView)findViewById(R.id.auto_screen_exp);
		exp_view.setGroupIndicator(null);
		exp_view.setOnGroupExpandListener(new OnGroupExpandListener() {
			
			@Override
			public void onGroupExpand(int groupPosition) {
				// TODO Auto-generated method stub
				for(int i=0;i<parent_datas.size();i++)
				{
					if(groupPosition!=i)
						exp_view.collapseGroup(i);
					//else
						
				}
			}
		});
		gallery = (ViewFlow)findViewById(R.id.auto_screen_viewflow);
		gallery.setAdapter(new GalleryAdapter(this, images));
		indicator = (CircleFlowIndicator) findViewById(R.id.auto_screen_indicator);
		
		gallery.setOnViewSwitchListener(new ViewSwitchListener() {
			
			@Override
			public void onSwitched(View view, int position) {
				// TODO Auto-generated method stub
				gal_pos=position;
			}
		});
		zar_oruulah_image = (ImageView)findViewById(R.id.car_zar_oruulah);
		zar_oruulah_image.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(AutoViewActivity.this, ZarOruulahActivity.class));
				overridePendingTransition(R.anim.right_in, R.anim.no_anim);
			}
		});
		full_screen = (TextView)findViewById(R.id.auto_screen_fullscreen);
		full_screen.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(images.size()==0)
				{
					Toast.makeText(AutoViewActivity.this, "Зураггүй байна", 2000).show();
				}
				else
				{
					Intent intent = new Intent(AutoViewActivity.this, GalleryView.class);
					Bundle bundle = new Bundle();
					bundle.putInt("pos", gal_pos);
					bundle.putStringArrayList("array", images);
					intent.putExtras(bundle);
					startActivity(intent);
					overridePendingTransition(R.anim.right_in, R.anim.no_anim);
				}
			}
		});
		tv_name=(TextView)findViewById(R.id.auto_screen_name);
		createTitleComponents();
		
		//focusOnView();
		findViewById(tv_id).setBackgroundResource(R.drawable.text_background);
		focusOnView();
	}

}
